<?php
declare (strict_types = 1);

namespace app\home\controller;

use app\BaseController;
use app\common\model\Post\Post as PostModel;
use app\common\model\Post\Comment as CommentModel;
use app\common\model\User\User as UserModel;
use app\common\model\User\Record as RecordModel;
use app\common\validate\Post\Comment as CommentValiDate;
use app\common\validate\User\Record as RecordValiDate;
use think\exception\ValidateException;

class Comment extends BaseController
{
    // 设置控制器中间件
    protected $middleware = [
        \app\home\middleware\LoginAuth::class
    ];

    protected function initialize()
    {
        parent::initialize();

        $this->CommentModel = new CommentModel();
    }

    public function add()
    {
        if($this->request->isPost())
        {
            $LoginUser = $this->request->LoginUser;

            $postid = $this->request->param('postid');

            $pid = $this->request->param('pid');

            $post = PostModel::find($postid);

            if(!$post)
            {
                $this->error('帖子不存在，无法评论');
            }

            $content = $this->request->param('content');

            // 评论数据
            $data = [
                'content' => $content,
                'userid' => $LoginUser['id'],
                'postid' => $postid,
                'accept' => 0
            ];

            if($pid)
            {
                // 处理回复的评论

                $level = CommentModel::where(['id' => $pid])->value('level');

                $data['pid'] = $pid;
                $data['level'] = $level + 1;
            }else{
                $data['pid'] = 0;
                $data['level'] = 0;
            }

            try {
                validate(CommentValiDate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getMessage());
            }

            $result = $this->CommentModel->save($data);

            if($result != FALSE)
            {
                $this->success('评论成功');
            }else{
                $this->error('评论失败');
            }
        }
    }
    public function like()
    {
        if($this->request->isAjax())
        {
            $commentid = $this->request->param('commentid');

            $LikeStr = $this->CommentModel->where('id',$commentid)->value('like');

            $LikeArr = explode(',',(String)$LikeStr);

            $LikeArr = array_filter($LikeArr);

            $userid = $this->request->LoginUser['id'];

            

            if(in_array($userid,$LikeArr))
            {
                $arr = [];
                // 已点赞
                foreach($LikeArr as $item)
                {
                    if($userid == $item)
                    {
                        continue;
                    }

                    $arr[] = $item;
                    
                }

                $LikeStr = implode(',',$arr);

                $result = $this->CommentModel->update(['like' => $LikeStr],['id' => $commentid]);

                if($result !== FALSE)
                {
                    $this->success('取消点赞成功');
                }else{
                    $this->error('取消点赞失败');
                }
                
            }else{
                // 未点赞
                $LikeArr[] = $userid;

                $LikeStr = implode(',',$LikeArr);

                $result = $this->CommentModel->update(['like' => $LikeStr],['id' => $commentid]);

                if($result !== FALSE)
                {
                    $this->success('点赞成功');
                }else{
                    $this->error('点赞失败');
                }
            }
        }
    }
    public function accept()
    {
        if($this->request->isAjax())
        {
            $commentid = $this->request->param('commentid');

            $comment = $this->CommentModel->find($commentid);

            $post = PostModel::find($comment['postid']);

            $User = UserModel::find($comment['userid']);

            if(!$comment)
            {
                $this->error('该评论不存在，无法采纳');
            }

            if(!$post)
            {
                $this->error('该帖子不存在，无法采纳');
            }

            if(!$User)
            {
                $this->error('用户不存在，无法采纳');
            }

            if($comment['accept'] > 0 && $post['accept'] > 0)
            {
                $this->error('该帖子已有采纳，无法采纳');
            }

            /* 
                评论表 更新采纳字段
                帖子表 需要更新采纳人字段
                用户表 悬赏积分加到用户
                消费记录 新增获取到积分记录
            */

            CommentModel::startTrans();
            PostModel::startTrans();
            UserModel::startTrans();
            RecordModel::startTrans();


            // 更新评论表
            $comment->accept = 1;

            $CommentStatus = $comment->save();

            if($CommentStatus === FALSE)
            {
                $this->error('评论采纳状态更新失败');
            }

            // 更新帖子表
            $post->accept = $comment['userid'];

            $PostStatus = $post->save();

            if($PostStatus === FALSE)
            {
                CommentModel::rollback();
                $this->error('帖子采纳人更新失败');
            }

            // 更新用户表
            $point = bcadd((String)$User['point'],(String)$post['point']);

            $User->point = $point;

            $UserStatus = $User->save();

            if($UserStatus === FALSE)
            {
                CommentModel::rollback();
                PostModel::rollback();
                $this->error('用户积分更新失败');
            }

            // 新增消费记录
            $RecordData = [
                'point' => $post['point'],
                'content' => "您发表的评论：{$comment['content']}获得了{$post['point']}积分",
                'state' => 2,
                'userid' => $comment['userid']
            ];


            try {
                validate(RecordValiDate::class)->check($RecordData);
            } catch (ValidateException $e) {
                CommentModel::rollback();
                PostModel::rollback();
                UserModel::rollback();
                $this->error($e->getMessage());
            }

            $Record = new RecordModel();

            $RecordStatus = $Record->save($RecordData);

            if($RecordStatus === FALSE)
            {
                CommentModel::rollback();
                PostModel::rollback();
                UserModel::rollback();
                $this->error('新增消费记录失败');
            }

            if($CommentStatus === FALSE || $PostStatus === FALSE || $UserStatus === FALSE || $RecordStatus === FALSE)
            {
                CommentModel::rollback();
                PostModel::rollback();
                UserModel::rollback();
                RecordModel::rollback();
                $this->error('采纳失败');
            }else{
                CommentModel::commit();
                PostModel::commit();
                UserModel::commit();
                RecordModel::commit();
                $this->success('采纳成功');
            }

        }
    }
}